package org.neframework.webtest.interceptor.tip;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.neframework.webtest.util.web.cookie.CookieTools;

import org.neframework.webtest.base.BaseController;
import com.tmsps.neframework.core.utils.ChkTools;
import com.tmsps.neframework.core.utils.JsonTools;
import com.tmsps.neframework.mvc.annotation.RequestMapping;
import com.tmsps.neframework.mvc.annotation.ResponseBody;
import com.tmsps.neframework.mvc.core.NeBaseController;
import com.tmsps.neframework.mvc.plugin.Tip;
import com.tmsps.neframework.mvc.web.interceptor.Interceptor;

/**
 * 提示消息拦截器
 * 
 * @author 冯晓东
 *
 */
@RequestMapping("/")
public class TipInterceptor implements Interceptor {

	@Override
	public boolean before(NeBaseController action, Method method, HttpServletRequest request, HttpServletResponse response) {
		BaseController baseAction = (BaseController) action;

		String tipJson = CookieTools.getAttribute("tip", request);
		if (ChkTools.isNotNull(tipJson)) {
			Tip tip = (Tip) JsonTools.jsonStrToJsonObject(tipJson, baseAction.tip.getClass());
			if (tip != null && ChkTools.isNotNull(tip.getMsg())) {
				baseAction.tip = tip;
			} else {
				baseAction.tip = new Tip();
			}
		} else {
			baseAction.tip = new Tip();
		}
		return true;
	}

	@Override
	public boolean after(NeBaseController action, Method method, HttpServletRequest request, HttpServletResponse response) {
		BaseController baseAction = (BaseController) action;

		if (!method.isAnnotationPresent(ResponseBody.class)) {
			CookieTools.setAttribute("tip", baseAction.tip.toString(), response);
		}
		return true;
	}

}
